<template>
  <div class="page search-page">
    <div class="handlePart">
      <el-form :inline="true" :model="form">
        <el-form-item label="站点名称：">
          <el-select size="small" v-model="form.qualityStationId" filterable placeholder="请选择">
            <el-option
              v-for="item in jclxOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="监测时间：">
          <el-date-picker
            v-model="monthRange"
            type="monthrange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            format="yyyy-MM"
            value-format="yyyy-MM">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button size="small" type="warning" icon="el-icon-clear" @click="clear">清空</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="success" icon="el-icon-download" @click="exportExcel">数据导出</el-button>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="add">新增</el-button>
          <el-button size="small" type="danger" icon="el-icon-delete" @click="dels">删除</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-show="activeName == '网格视图'">
      <div class="tablePart">
        <el-table ref="listTable" :data="list" :height="'calc(100vh - 290px)'" stripe style="width: 100%">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="序号" type="index" align="center" width="55"></el-table-column>
          <el-table-column prop="qualityStationName" label="站点名称" align="center"> </el-table-column>
          <el-table-column prop="date" label="监测日期(年月)" align="center"> </el-table-column>
          <el-table-column prop="quality" label="水质级别" align="center"> </el-table-column>
          <el-table-column prop="qualityText" label="描述" align="center"> </el-table-column>
          <el-table-column fixed="right" label="操作" align="center" width="160">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-edit" title="编辑" @click="edit(scope.row)"></el-button>
              <el-button type="text" icon="el-icon-delete" title="删除" @click="del(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagePart">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
                       :page-sizes="[10, 20, 30, 40, 50]" :page-size="size" layout="total, sizes, prev, pager, next, jumper"
                       :total="total">
        </el-pagination>
      </div>
    </div>
    <div class="chart" v-show="activeName == '图像视图'">
      <div id="myChart" class="chartDiv" ></div>
    </div>
    <el-radio-group v-model="activeName" class="tab-group">
      <el-radio-button label="网格视图"></el-radio-button>
      <el-radio-button label="图像视图"></el-radio-button>
    </el-radio-group>
    <EditDialog ref="editDialogRef" @listInit="listInit" />
  </div>
</template>
<script>
import EditDialog from './editDialog.vue';
// import DetailDialog from './detailDialog.vue';
export default {
  data() {
    return {
      form: {
        dateBegin: '',
        dateEnd: '',
        keywords: '',
        qualityStationId:'',
        orderBy: "date"
      },
      activeName:'网格视图',
      monthRange:[],
      list: [],
      jclxOptions: [],
      isVisible: true,
      page: 1,
      size: 10,
      total: 0,
      selectList: [],
    };
  },
  created(){
  },
  async mounted() {
    await this.getparams();
    this.listInit();
    this.chartInit()
  },
  methods: {
    async getparams(){
      let res = await this.$api.getHasWaterQualityStationName({
        keywords: this.keywords,
      });
      if (res && res.code == 200) {
        this.jclxOptions = res.data || [];
        this.form.qualityStationId = this.jclxOptions[0].id;
      }
    },
    listInit() {
      if(this.monthRange && this.monthRange.length){
        this.form.dateBegin = this.monthRange[0]
        this.form.dateEnd = this.monthRange[1]
      }else {
        this.form.dateBegin = ''
        this.form.dateEnd = ''
      }
      let params = Object.assign({},this.form,{
        size: this.size,
        page: this.page,
        orderBy: "date"
      })
      this.$api.getWaterQualityMonitorList(params).then((res) => {
        this.list=[]
        if(res && res.code == 200){
          let data = res.data || {}
          this.total = data.total || 0
          this.list = data.list || []
        }
      })
    },
  async exportExcel() {
    if(this.monthRange && this.monthRange.length){
        this.form.dateBegin = this.monthRange[0]
        this.form.dateEnd = this.monthRange[1]
      }else {
        this.form.dateBegin = ''
        this.form.dateEnd = ''
      }
      let params = Object.assign({},this.form,{
        size: 99999,
        page: 1,
        orderBy: "date"
      })
    const allRes = await this.$api.getWaterQualityMonitorList(params);
    if (allRes && allRes.code === 200) {
      const data = allRes.data.list || [];
      const tableRef = this.$refs.listTable;
      this.$exportExcel(data,tableRef, "水质站水质监测管理")
    } else {
      this.$message.error('获取数据失败');
    }
  },
    //清空
    clear() {
      this.monthRange=[]
      this.end=''
      this.start= ''
      this.keywords=''
      this.form.qualityStationId = this.jclxOptions[0].id;
      Object.assign(this.form, this.$options.data().form)
      this.listInit()
      this.chartInit()
    },
    // 查询
    search(){
      this.page = 1
      if(this.form.qualityStationId == ''){
        this.$notify.warning({
          title: '警告',
          message: '请选择站点名称！'
        });
        return
      }
      this.listInit()
      this.chartInit()
    },
    // 新增
    add() {
      this.$refs.editDialogRef.showModal('add');
    },
    // 编辑
    edit(row) {
      this.$refs.editDialogRef.showModal('edit', row);
    },
    // 配置
    config(row){
      // this.$refs.detailDialogRef.showModal(row);
    },
    // 删除
    del(row){
      this.$confirm('数据删除后将无法恢复，确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.delWaterQualityMonitor([row.id]).then(res => {
          if(res && res.code == 200){
            this.$notify.success({
              title: '成功',
              message: '删除成功!'
            });
            this.listInit()
          }
        })
      }).catch(() => {});
    },
    // 批量删除
    dels(){
      if(this.selectList.length == 0){
        this.$notify.warning({
          title: '警告',
          message: '请至少选择一条数据！'
        });
        return
      }
      let ids = []
      this.selectList.forEach(l => {
        ids.push(l.id)
      })
      this.$confirm('数据删除后将无法恢复，确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.delWaterQualityMonitor(ids).then(res => {
          if(res && res.code == 200){
            this.$notify.success({
              title: '成功',
              message: '删除成功!'
            });
            this.listInit()
          }
        })
      }).catch(() => {});
    },
    // 多选
    handleSelectionChange(val) {
      this.selectList = val;
    },
    // size change
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.page = 1;
      this.size = val;
      this.listInit();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page = val;
      this.listInit();
    },
    chartInit() {
      if(this.monthRange && this.monthRange.length){
        this.form.dateBegin = this.monthRange[0]
        this.form.dateEnd = this.monthRange[1]
      }else {
        this.form.dateBegin = ''
        this.form.dateEnd = ''
      }
      let params = Object.assign({},this.form,{
        size: 0,
        page: 0,
        orderBy: "date"
      })
      this.$api.getAllWaterQualityMonitor(params).then((res) => {
        if (res && res.code == 200) {
          let data = res.data || []
          let xAxisData = []
          let serieData = []
          data.forEach(l => {
            l.date = l.date ? l.date : ''
            xAxisData.push(l.date)
            serieData.push(l.quality)
          })
          this.getChartInit(xAxisData, serieData)
        }
      })
    },
    getChartInit(xAxisData, serie1Data) {
      let item1 = {
        name: '水质级别',
        type: 'line',
        smooth: true,
        barMaxWidth: '60',
        // areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        color: ['#3398db'],
        data: serie1Data,
      }

      let legendData = ['水质级别']
      let series = [item1]
      let myChart = this.$echarts.init(document.getElementById('myChart'));
      let option = {
        title: {
          text: '水质级别变化趋势',
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `<div>日期: ${params[0].name}</div><div>水质级别: ${params[0].value}</div>`;
          }
        },
        legend: {
          data: legendData,
        },
        toolbox: {
          show: true,
          feature: {
            restore: {},
            saveAsImage: {}
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
          {
            start: 0,
            end: 100
          }
        ],
        yAxis: {
          type: 'value',
          axisTick: {
            show: false
          },
          axisLine: {
            show: false
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: series
      };
      option && myChart.setOption(option);

      let _this = this
      // 监听toolbox中的事件
      /* myChart.on('magictypechanged', function (params) {
         console.log(params)
         _this.form.chartType = params.currentType == 'line' ? '折线图' : '柱状图'
         _this.chartInit()

       });*/

      window.addEventListener("resize", function () {
        myChart.resize();
      });
    },
  },
  components: { EditDialog }
};
</script>

<style lang="less" scoped>
.tips {
  cursor: pointer;
  margin-left: -8px;
  margin-right: 5px;
  color:#2196f3;
}
.tabbtn {
  text-align: left;
  padding: 20px 0;
}
.page.search-page {
  position: relative;


  .chart {
    width: calc(100% - 20px);
    height: calc(100% - 80px);
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .chartDiv {
    width: calc(100vw - 20px);
    height:calc(100vh - 290px);
  }

  .tab-group {
    position: absolute;
    bottom: 10px;
    left: 10px;
  }
}
</style>
